import sort_ascii from "../utils/signature"
import axios from "axios";
import router from "@/router";
import {
    Message
} from "element-ui";
const service = axios.create({
    // baseURL: "https://api.zjht.zgdjkpt.com/mch/",
    baseURL: window.LOCATIONURL, // "https://test.zjht.zgdjkpt.com/mch/",
    timeout: 80000,
});
import md5Libs from "@/utils/md5";
let token = "0"
var appkey = "4142d543b5308fafc655e0041a1b7edd68b0a992"
var secret = "26a4019321fb71311646ceef54cbb12ac1cdc6ca"
var cdnkey = "D541j17rx2JXQkZ1p9xNj1ZbJSW8ghG9r0bd3lB8"
// var version = "0.0.01"
const get_apiurl = (i, b) => {
    let timestamp = parseInt(new Date().getTime() / 1000);
    let none_str = str_rand(40);
    let version = "3.1.1"
    let token = sessionStorage.getItem("token") || '0';
    let p1 = {
        appkey: appkey,
        model: 'webapp',
        os: 'windows',
        version: version,
        platform: 'web',
        none_str: none_str
    };
    let p2 = Object.keys(p1).map(function (key) {
        return (key) + "=" + (p1[key]);
    }).join("&");
    let s1 = 'action=' + i + '&appkey=' + appkey + '&model=' + p1.model + '&os=' + p1.os + '&version=' + version + '&timestamp=' + timestamp + '&platform=' + p1.platform + '&none_str=' + none_str + '&token=' + token;
    let s2 = md5Libs.md5(s1) + secret;
    let s3 = md5Libs.md5(s2);
    // console.log("i"i)
    let a1 = '/' + b + '/' + i + '.json-' + timestamp + '-' + s3 + '-' + token + '-' + cdnkey;
    let a2 = timestamp + '-' + s3 + '-' + token + '-' + md5Libs.md5(a1);
    return '/' + b + '/' + i + '.json?' + p2 + '&access_token=' + a2;
}
const str_rand = (l, c) => {
    let min = 0,
        _str = '';
    l = l || 32;
    c = c || '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    for (var i = 0, index; i < l; i++) {
        _str += c[parseInt(Math.random() * c.length)];
    }
    return _str;
}

let flag = false //不放行
// let base = 'webmchapi';
service.interceptors.request.use(
    (config) => {
        config.url = get_apiurl(config.url, config.base ? config.base : 'webmchapi')
        if (config.method == 'post') {
            config.data['platform'] = 'sys_web'
        }
        config.data['timestamp'] = Date.parse(new Date()) / 1000;
        config.data['sign'] = sort_ascii(config.data);

        //如果登录之后  长时间未操作
        if (token !== '0') {
            if (config.data['timestamp'] - Number(sessionStorage.getItem("last_req_time")) > 3000) { //50分钟
                Message({
                    message: "您长时间未操作，请重新登陆！",
                    type: "warning",
                    showClose: true,
                });
                sessionStorage.clear()
                router.replace({
                    path: "/login",
                });
            } else {
                //续签
                let expire_time = Number(sessionStorage.getItem('expire_time')) - config.data['timestamp']
                if (expire_time < 3200) { //小于*小时信息续签  调接口
                    axios({
                        url: window.LOCATIONURL + get_apiurl("login/renewToken", 'webadminapi'),
                        method: 'POST',
                        params: {
                            timestamp: Date.parse(new Date()) / 1000, //当前时间
                            sign: sort_ascii({})
                        },
                    }).then(res => {
                        sessionStorage.setItem("token", res.data.data.token);
                        sessionStorage.setItem("username", res.data.data.name);
                        sessionStorage.setItem("expire_time", res.data.data.expire_time);
                    })
                }
            }

        }

        //可添加请求头
        if (token == '0' && sessionStorage.getItem("token")) {
            token = sessionStorage.getItem("token");
        }
        return config;
    },
    (error) => {
        // ("出错啦", error); // for debug
        Promise.reject(error);
    }
);

service.interceptors.response.use(
    (response) => {
        if (token !== '0') {
            sessionStorage.setItem("last_req_time", Date.parse(new Date()) / 1000)
        }
        if (response.data.err === 0) {
            return response.data;
        } else if (response.data.err === 20011) {
            //信息过期重新登录
            router.replace({
                path: "/login",
            });
            Message({
                message: response.data.msg,
                type: "error",
                showClose: true,
            });
        } else {
            return response.data;
        }
    },

    (error) => {
        //加载超时提示
        if (document.getElementsByClassName("el-message").length > 0) return false;
        Message({
            message: "加载超时，请稍后重试",
            type: "error",
            showClose: true,
        });
        // ("err" + error); // for debug
        return Promise.reject(error);
    }
);


export default service;